package com.marvels.approve.process.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.marvels.approve.common.service.IUploadFileService;
import com.marvels.approve.process.api.ApplyProvideConsumerApi;
import com.marvels.approve.process.dao.AttachmentInfoDao;
import com.marvels.approve.process.dto.LaAttachAtmeTypeViewDTO;
import com.marvels.approve.process.dto.LaAttachmentDTO;
import com.marvels.approve.process.service.AttachmentInfoService;
import com.marvels.common.constants.CaseNodeConstant;
import com.marvels.common.exception.MarvelsBusinessException;
import com.marvels.common.utils.MarvelsLogUtil;

@Service
public class AttachmentInfoServiceImpl implements AttachmentInfoService {

	@Autowired
	private AttachmentInfoDao attachmentInfoDao;

	@Autowired
	private ApplyProvideConsumerApi applyProvideConsumerApi;
	
	@Autowired
	private IUploadFileService uploadFileService;
	
	@Value("${marvels.file.upload.basepath}")
	private String nfsFileSystem;

	public List<LaAttachAtmeTypeViewDTO> selectAttachmentInfo(LaAttachmentDTO laAttachmentDTO) throws MarvelsBusinessException {
		List<LaAttachAtmeTypeViewDTO> mediaList = uploadFileService.getAttachmentsByViewKey(CaseNodeConstant.WOINTERVIEW.getCode(), laAttachmentDTO.getLoanId());
		return mediaList;
	}

	@Override
	public List<LaAttachAtmeTypeViewDTO> getAttachmentsByViewKey(LaAttachAtmeTypeViewDTO laAttachAtmeTypeView,String loanId) throws MarvelsBusinessException {
		if(StringUtils.isEmpty(loanId)){
			throw new MarvelsBusinessException("loanId不能为空");
		}
		if(laAttachAtmeTypeView == null || StringUtils.isEmpty(laAttachAtmeTypeView.getViewKey())){
			throw new MarvelsBusinessException("viewKey不能为空");
		}
		//获取当前支持的附件类型
		List<LaAttachAtmeTypeViewDTO> attachAtmeTypeList = applyProvideConsumerApi.getAttachAtmeTypeInfo(laAttachAtmeTypeView);
		if(CollectionUtils.isEmpty(attachAtmeTypeList)){
			return attachAtmeTypeList;
		}
		//获取所有支持附件类型的附件信息
		List<LaAttachmentDTO> attachmentList = attachmentInfoDao.getAttachmentsByAttachmentTypes(attachAtmeTypeList,loanId);
		if(CollectionUtils.isEmpty(attachmentList)){
			return attachAtmeTypeList;
		}
		//封装附件类型对应的附件信息
		for(int i=0;i<attachAtmeTypeList.size();i++){
			List<LaAttachmentDTO> attachments = new ArrayList<LaAttachmentDTO>();
			LaAttachAtmeTypeViewDTO type = attachAtmeTypeList.get(i);
			for(int j=0;j<attachmentList.size();j++){
				LaAttachmentDTO attach = attachmentList.get(j);
				if(StringUtils.equals(type.getAtmtType(), attach.getAtmtType())){
					attachments.add(attach);
				}
			}
			type.setLaAttachmentDTOList(attachments);
		}
		return attachAtmeTypeList;
	}

//	public static void main(String[] args) {
//		String str = "/imageview/2021/1/30/idCard_bd9b5d88-0180-43fd-bb04-105806a73d5e.jpg";
//		System.out.println(str.replaceAll("/imageview", "/jushou/upload/clsmp"));
//	}
	
	@Override
	public void loadAttachmentById(Long id, HttpServletRequest request, HttpServletResponse response)
			throws MarvelsBusinessException {
		if (id == null || id < 1) {
			throw new MarvelsBusinessException("附件id不能为空");
		}
		LaAttachmentDTO attachment = attachmentInfoDao.selectAttachmentById(id);
		if (attachment == null) {
			throw new MarvelsBusinessException("附件信息不存在, 附件id=" + id);
		}
		String realFilePath = nfsFileSystem+attachment.getFileLocation().replaceFirst("/imageview", nfsFileSystem);
		File file = new File(realFilePath);
		if (!file.exists()) {
			throw new MarvelsBusinessException("附件不存在, 附件id=" + id);
		}
		String fileName = attachment.getFileName();
		String fileType = "pdf";
		if(StringUtils.isNotEmpty(fileName)){
			fileType = fileName.substring(fileName.lastIndexOf(".")+1);
		}
		response.setContentType("application/"+fileType);
		byte[] data = null;
		InputStream in = null;
		OutputStream out = null;
		try {
			out = response.getOutputStream();
			in = new FileInputStream(file);
			data = new byte[in.available()];
			in.read(data);
			out.write(data);
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error("读取附件异常, 附件id=" + id, e);
			throw new MarvelsBusinessException("加载附件失败", e);
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					MarvelsLogUtil.getInstance().error("关闭附件流in异常, 附件id=" + id, e);
				}
			}
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					MarvelsLogUtil.getInstance().error("关闭附件流out异常, 附件id=" + id, e);
				}
			}
		}
	}
	
	/**根据贷款编号和类型查询附件
	 * @author 娄凯琦
	 * @date 2018年9月27日  
	 * @param laAttachmentDTO
	 * @return
	 * @throws MarvelsBusinessException
	 */
	@Override
	public List<LaAttachmentDTO> getAttachmentByLoanIdAndType(LaAttachmentDTO laAttachmentDTO)
			throws MarvelsBusinessException {
		if(laAttachmentDTO==null){
			throw new MarvelsBusinessException("传入参数为空!");
		}
		return attachmentInfoDao.selectByLoanIdAndType(laAttachmentDTO);
	}
	

}
